package utils;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;

public class QuizTasks extends AsyncTask<String, String, String> {

	JSONParser jsonParser = new JSONParser();
	JSONArray quizes = null;
	JSONArray questions = null;
	JSONArray answers = null;
	List<String> correctAnswers = new ArrayList<String>();
	
	static String validation = "";
	
	private final String QUIZ_LIST = "<li><a %EVENT%>%QUIZ%</a></li>";

	private String url_get_all_quizes = "http://weblabtutor.comyr.com/get_all_quizes.php";
	private String url_get_quiz = "http://weblabtutor.comyr.com/get_quizes_by_lesson.php";
	private String url_get_questions = "http://weblabtutor.comyr.com/get_questions_by_quiz.php";
	private String url_get_answers = "http://weblabtutor.comyr.com/get_answer_by_question.php";

	private final String TAG_SUCCESS = "success";
	private final String TAG_QUIZES = "quizes";
	private final String TAG_QUESTIONS = "questions";
	private final String TAG_ANSWERS = "answers";
	private final String TAG_ID = "id";
	private final String TAG_NAME = "name";
	private final String TAG_TEXT = "text";
	private final String TAG_CORRECT_ANSWER = "correct_answer";
	private final String TAG_LETTER = "letter";
	private final String TAG_LESSON = "Lesson_id";

	protected String doInBackground(String... args) {

		List<NameValuePair> params = new ArrayList<NameValuePair>();

		int score = 0;
		String finalOutput = "";

		if (args[0].equalsIgnoreCase("get_questions")) {
			String output = args[2];
			
			params.clear();
			params.add(new BasicNameValuePair("lesson_id", args[1]));
			JSONObject json = jsonParser.makeHttpRequest(url_get_quiz, "GET",
					params);

			Log.d("All Quizes: ", json.toString());

			try {
				int success = json.getInt(TAG_SUCCESS);
				if (success == 1) {
					quizes = json.getJSONArray(TAG_QUIZES);

					for (int i = 0; i < quizes.length(); i++) {
						JSONObject c = quizes.getJSONObject(i);
						String id = c.getString(TAG_ID);
						String name = c.getString(TAG_NAME);

						params.clear();
						params.add(new BasicNameValuePair("quiz_id", id));
						JSONObject question = jsonParser.makeHttpRequest(
								url_get_questions, "GET", params);

						int success1 = question.getInt(TAG_SUCCESS);
						if (success1 == 1) {
							questions = question.getJSONArray(TAG_QUESTIONS);
							for (int j = 0; j < questions.length(); j++) {
								JSONObject obj = questions.getJSONObject(j);
								String questionId = obj.getString(TAG_ID);
								String questionText = obj.getString(TAG_TEXT);
								String questionCorrectAnswer = obj
										.getString(TAG_CORRECT_ANSWER);
								correctAnswers.add(questionCorrectAnswer);

								finalOutput += output;
								finalOutput = finalOutput.replace("%QUESTION%",	questionText);

								params.clear();
								params.add(new BasicNameValuePair(
										"question_id", questionId));
								JSONObject answer = jsonParser.makeHttpRequest(
										url_get_answers, "GET", params);

								int success2 = answer.getInt(TAG_SUCCESS);
								if (success2 == 1) {
									answers = answer.getJSONArray(TAG_ANSWERS);
									for (int k = 0; k < answers.length(); k++) {
										JSONObject o = answers.getJSONObject(k);
										String answerText = o
												.getString(TAG_TEXT);
										String answerLetter = o
												.getString(TAG_LETTER);

										finalOutput = finalOutput.replace(
												"%ANSWER" + (k + 1) + "%",
												answerText);
										
										finalOutput = finalOutput.replace(
												"%C" + (k + 1) + "%",
												"correctRadio");
									}
								}

								finalOutput = finalOutput.replace("$X$",
										Integer.toString(j));
								
								if (args.length > 3) {
									if (args[3].equalsIgnoreCase("validate_answers")) {
										String[] answers = args[4].split(" ");
										finalOutput = validate(finalOutput,questionCorrectAnswer,j,answers);
									}
								}
							}
						}

						if (args.length > 3) {
							if (args[3].equalsIgnoreCase("validate_answers")) {
								String[] answers = args[4].split(" ");
								for (int s = 0; s < answers.length; s++) {
									String x = correctAnswers.get(s);
									if (answers[s].equalsIgnoreCase(x))
										score++;
								}
							}
							validation = finalOutput + "<br/><center><b> Test score is " + score + "</b></center>";
						}
					}

				} else {
					Toast.makeText(null, "Error", Toast.LENGTH_LONG);
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}
		else
		{
			if(args[0].equalsIgnoreCase("get_quizes")){
				
				JSONObject json = jsonParser.makeHttpRequest(url_get_all_quizes, "GET", params);

				Log.d("All Quizes: ", json.toString());

				try {
					int success = json.getInt(TAG_SUCCESS);
					if (success == 1) {
						quizes = json.getJSONArray(TAG_QUIZES);

						for (int i = 0; i < quizes.length(); i++) {
							JSONObject c = quizes.getJSONObject(i);

							String id = c.getString(TAG_ID);
							String name = c.getString(TAG_NAME);
							String lesson_id = c.getString(TAG_LESSON);

							finalOutput += QUIZ_LIST;
							finalOutput = finalOutput.replace("%QUIZ%", name);
							finalOutput = finalOutput.replace("%EVENT%", "onclick=\"return quizRedirect1("+lesson_id+");\"");
						}
						return finalOutput;
					} else {
						Toast.makeText(null, "Error", Toast.LENGTH_LONG);
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
			else
				if(args[0].equalsIgnoreCase("get_validation"))
					return validation;
		}
		
		if (args.length > 3) 
			return finalOutput + "<br/><center><b> Test score is " + score + "</b></center>";
		else
			return finalOutput;
	}

	protected String validate(String finalOutput, String questionCorrectAnswer, int j, String[] answers) {

		if (questionCorrectAnswer.equalsIgnoreCase("a")) {
			if(answers[j].equalsIgnoreCase("a"))
				finalOutput = finalOutput.replace("$N$", "1");
			else
				finalOutput = finalOutput.replace("$N$", "2");
			finalOutput = finalOutput.replace("$A$", "checked=\"checked\"");
			finalOutput = finalOutput.replace("$B$", "");
			finalOutput = finalOutput.replace("$C$", "");
			finalOutput = finalOutput.replace("$D$", "");
		} else if (questionCorrectAnswer.equalsIgnoreCase("b")) {
			if(answers[j].equalsIgnoreCase("b"))
				finalOutput = finalOutput.replace("$N$", "1");
			else
				finalOutput = finalOutput.replace("$N$", "2");
			finalOutput = finalOutput.replace("$B$", "checked=\"checked\"");
			finalOutput = finalOutput.replace("$A$", "");
			finalOutput = finalOutput.replace("$C$", "");
			finalOutput = finalOutput.replace("$D$", "");
		} else if (questionCorrectAnswer.equalsIgnoreCase("c")) {
			if(answers[j].equalsIgnoreCase("c"))
				finalOutput = finalOutput.replace("$N$", "1");
			else
				finalOutput = finalOutput.replace("$N$", "2");
			finalOutput = finalOutput.replace("$C$", "checked=\"checked\"");
			finalOutput = finalOutput.replace("$B$", "");
			finalOutput = finalOutput.replace("$A$", "");
			finalOutput = finalOutput.replace("$D$", "");
		} else {
			if(answers[j].equalsIgnoreCase("d"))
				finalOutput = finalOutput.replace("$N$", "1");
			else
				finalOutput = finalOutput.replace("$N$", "2");
			finalOutput = finalOutput.replace("$D$", "checked=\"checked\"");
			finalOutput = finalOutput.replace("$B$", "");
			finalOutput = finalOutput.replace("$C$", "");
			finalOutput = finalOutput.replace("$A$", "");
		}

		return finalOutput;
	}
}
